//
//  PPCommentTimelineViewController.m
//  pickpic
//
//  Created by Jinxiao on 10/6/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPCommentTimelineViewController.h"
#import "PPProfileViewController.h"

#import "PPTimelineDetailCommentView.h"

#import "PPCommentTimelineTableViewCell.h"

static const NSInteger kCount = 50;
@interface PPCommentTimelineViewController ()
@property (readwrite, nonatomic, strong) PPTimelineDetailCommentView *commentView;
@property (readwrite, nonatomic, assign) CGFloat keyboardTop;
@property (nonatomic, strong) NSNumber *next;
@end

@implementation PPCommentTimelineViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    _keyboardTop = self.view.height;

    self.title = @"评论";

    [self.tableView registerClass:[PPCommentTimelineTableViewCell class] forCellReuseIdentifier:@"commentCell"];

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    UIControl *dismissalControl = [[UIControl alloc] init];
    [dismissalControl addTarget:self action:@selector(dismissalControlDidPressed) forControlEvents:UIControlEventTouchUpInside];
    self.tableView.backgroundView = dismissalControl;

    _commentView = [[PPTimelineDetailCommentView alloc] init];
    [_commentView.sendButton addTarget:self action:@selector(sendButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_commentView];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveKeyboardWillChangeFrameNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];

    if(_comment != nil) {
        _commentView.target = _comment.sender;
        _commentView.targetCommentID = _comment.commentID;
        _commentView.bottom = _keyboardTop; // 避免评论条从天而降
        [_commentView beginEdit];
    }
}

- (void)didReceiveKeyboardWillChangeFrameNotification:(NSNotification *)notification {
    CGRect endRect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [[notification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];

    CGRect rect = [[[UIApplication sharedApplication] keyWindow] convertRect:endRect toView:self.view];

    _keyboardTop = CGRectGetMinY(rect);

    [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionBeginFromCurrentState|(curve << 16) animations:^{
        _commentView.bottom = _keyboardTop;
    } completion:nil];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    _commentView.frame = CGRectMake(0, _keyboardTop - 46, self.view.width, 46);
}

- (void)dismissalControlDidPressed {
    UITextField *textField = [_commentView valueForKey:@"textField"];
    [textField resignFirstResponder];
}

- (void)sendButtonDidPressed {
    [_commentView willSend];

    NSNumber *ID = nil;
    NSNumber *type = nil;

    if(_albumID > 0) {
        ID = @(_albumID);
        type = @(1);
    } else {
        ID = @(_imageID);
        type = @(2);
    }

    __weak typeof(self)weakSelf = self;
    [PPNetworkService sendCommentWithType:type ID:ID parentID:_commentView.targetCommentID ? : @(-1) content:_commentView.text version:_version callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        if(error == nil) {
            if (strongSelf.commentView.targetCommentID)
            {
                [MobClick event:@"155"];
            }
            else
            {
                [MobClick event:@"151"];
            }


            if([strongSelf.delegate respondsToSelector:@selector(commentTimelineViewController:didInsertComment:)]) {
                PPTimelineCommentObject *comment = [PPTimelineCommentObject commentForParameters:data];
                [strongSelf.delegate commentTimelineViewController:strongSelf didInsertComment:comment];
            }

            [strongSelf fetchNewItems];
        } else {
            [strongSelf.navigationController.view toastMessage:error.networkPrompt];
        }
    }];

    [_commentView didSend];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.items.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    PPTimelineCommentObject *comment = [self.items safeObjectAtIndex:indexPath.row];

    return [PPCommentTimelineTableViewCell heightForComment:comment constrainedSize:CGSizeMake(tableView.width, 1000)];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PPCommentTimelineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commentCell"];
    cell.delegate = self;
    PPTimelineCommentObject *comment = [self.items safeObjectAtIndex:indexPath.row];
    cell.comment = comment;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    PPTimelineCommentObject *comment = [self.items safeObjectAtIndex:indexPath.row];

    _commentView.target = comment.sender;
    _commentView.targetCommentID = comment.commentID;

    [_commentView beginEdit];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if([_ownerID isEqualToString:DGCurrentAccount.userID]) {
        return YES;
    } else {
        PPTimelineCommentObject *comment = [self.items safeObjectAtIndex:indexPath.row];

        if([comment.sender.userID isEqualToString:DGCurrentAccount.userID]) {
            return YES;
        }
    }

    return NO;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    [MobClick event:@"153"];
    return UITableViewCellEditingStyleDelete;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if(editingStyle == UITableViewCellEditingStyleDelete) {
        [MobClick event:@"154"];
        PPTimelineCommentObject *comment = [self.items safeObjectAtIndex:indexPath.row];

        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

        __weak typeof(self)weakSelf = self;
        NSNumber *type = _albumID ? @1 : @2;
        [PPNetworkService deleteCommentWithCommentID:comment.commentID type:type callback:^(id data, NSError *error) {
            __strong typeof(weakSelf)strongSelf = weakSelf;

            if(strongSelf == nil) {
                return;
            }

            [hud hide:YES];

            if(error == nil) {
                if([_delegate respondsToSelector:@selector(commentTimelineViewController:didRemoveComment:)]) {
                    [_delegate commentTimelineViewController:self didRemoveComment:comment];
                }

                [strongSelf fetchNewItems];
            } else {
                [strongSelf.navigationController.view toastMessage:error.networkPrompt];
            }
        }];
    }

    tableView.editing = NO;
}

#pragma mark - Timeline

- (void)fetchNewItems {
    [super fetchNewItems];

    NSNumber *ID = nil;
    NSNumber *type = nil;

    if(_albumID > 0) {
        ID = @(_albumID);
        type = @(1);
    } else {
        ID = @(_imageID);
        type = @(2);
    }

    _next = nil;
    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchCommentListWithType:type ID:ID start:_next limit:kCount version:_version callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        [weakSelf didReceiveNewResult:data ? : error];
    }];
}

- (void)fetchMoreItems {
    [super fetchMoreItems];

    NSNumber *ID = nil;
    NSNumber *type = nil;

    if(_albumID > 0) {
        ID = @(_albumID);
        type = @(1);
    } else {
        ID = @(_imageID);
        type = @(2);
    }

    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchCommentListWithType:type ID:ID start:_next limit:kCount version:_version callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        [self didReceiveMoreResult:error ? : data];
    }];
}

- (NSArray *)didReceiveNewResult:(id)result {
    NSArray *items = [super didReceiveNewResult:result];

    if([_next integerValue] != -1) {
        self.scrollWrapper.enableLoadMore = YES;
    } else {
        self.scrollWrapper.enableLoadMore = NO;
    }

    return items;
}

- (NSArray *)didReceiveMoreResult:(id)result {
    NSArray *items = [super didReceiveMoreResult:result];

    if([_next integerValue] != -1) {
        self.scrollWrapper.enableLoadMore = YES;
    } else {
        self.scrollWrapper.enableLoadMore = NO;
    }

    return items;
}

- (NSArray *)itemsFromResult:(id)result {
    NSMutableArray *items = [NSMutableArray array];

    self.next = [[result validDictionary] validNumberForKey:@"next"];

    for(NSDictionary *parameters in [result validArrayForKey:@"comments"]) {
        PPTimelineCommentObject *comment = [PPTimelineCommentObject commentForParameters:parameters];

        NSString *content = nil;

        if(comment.receiver == nil) {
            content = comment.content;
        } else {
            content = [NSString stringWithFormat:@"回复 \u200B%@: %@", comment.receiver.name, comment.content];
        }

        DGCoreTextEditor *editor = [[DGCoreTextEditor alloc] initWithString:content];
        editor.defaultColor = [UIColor colorWithRGBHex:0x4d4d4d];
        editor.defaultFont = [UIFont systemFontOfSize:15];

        DGCoreTextPatternSetting *nameSetting = [[DGCoreTextPatternSetting alloc] init];
        nameSetting.predicate = @"\u200B[\\u4e00-\\u9fa5\\w\\-]+";
        nameSetting.defaultFont = [UIFont systemFontOfSize:15];
        nameSetting.highlightedFont = [UIFont systemFontOfSize:15];
        nameSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
        nameSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

        __weak typeof(self)weakSelf = self;
        nameSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
            [weakSelf didPressedCommentReceiver:comment];
        };
        [editor preprocessWithPatternSetting:nameSetting];
        [editor process];

        comment.editor = editor;

        [items addObject:comment];
    }

    return items;
}

- (UIEdgeInsets)preferredScrollInsets {
    return UIEdgeInsetsMake(64, 0, 46, 0);
}

- (void)didPressedCommentReceiver:(PPTimelineCommentObject *)comment {
    PPProfileViewController *profileViewController = [[PPProfileViewController alloc] init];
    profileViewController.userID = comment.receiver.userID;
    [self.navigationController pushViewController:profileViewController animated:YES];
}

@end
